package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
)

func lala(c *gin.Context) {
	//xx := c.Query("name")
	xx := c.DefaultQuery("name", "wwww")
	c.String(http.StatusOK, xx)
}

func zjj(c *gin.Context) {
	fmt.Printf("zhongjianjian")
	c.Next()
}

func main() {
	r := gin.Default()

	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello gin")
	})

	//au := r.Group("/admin",gin.BasicAuth(gin.Accounts{
	//	"xx": "xx",
	//}))

	r.GET("/xx2/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)
	})

	r.GET("/xx", func(c *gin.Context) {
		c.String(http.StatusOK, "lalala")
	})

	r.GET("/xx1/:name", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"name": c.Param("name"),
		})
	})

	//r.Use(zjj)
	r.GET("/xx2", lala)

	v1 := r.Group("/v1")
	{
		v1.GET("/xx", func(context *gin.Context) {
			context.String(http.StatusOK, "v1/xx")
		})
	}

	r.POST("/xx", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg": c.PostForm("msg"),
		})
	})

	r.POST("/upload", func(c *gin.Context) {
		fmt.Print("upload xxx")
		file, header, err := c.Request.FormFile("image")
		filename := header.Filename
		fmt.Printf(header.Filename)

		out, err := os.Create("templates/" + filename)
		if err != nil {
			log.Fatal(err)
		}

		defer out.Close()
		_, err = io.Copy(out, file)

		if err != nil {
			log.Fatal(err)
		}
		c.String(http.StatusCreated, "upload successful")
	})

	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "hello gin",
		})
	})

	r.GET("/redirect", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
	})

	r.LoadHTMLGlob("src/goxx/html/templates/*")
	r.Run(":8080")
}
